package middleware

import (
	"gitee.com/bobo-rs/creative-framework/pkg/response"
	"gitee.com/bobo-rs/creative-services/enums"
	"gitee.com/bobo-rs/creative-services/framework/model"
	"gitee.com/bobo-rs/creative-services/framework/service"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"net/http"
)

type sMiddleware struct {
}

func init() {
	service.RegisterMiddleware(New())
}

func New() *sMiddleware {
	return &sMiddleware{}
}

// Ctx 上下文自定义初始化
func (m *sMiddleware) Ctx(r *ghttp.Request) {
	service.BizCtx().Init(r, &model.Context{
		Data: make(map[enums.ContextDataKey]interface{}),
	})

	// 继续执行
	r.Middleware.Next()
}

// ResponseHandler 响应资源处理
func (m *sMiddleware) ResponseHandler(r *ghttp.Request) {
	r.Middleware.Next()
	// 资源返回不处理
	if r.Response.BufferLength() > 0 {
		return
	}

	var (
		msg  string
		err  = r.GetError()
		res  = r.GetHandlerResponse()
		code = gerror.Code(err)
	)

	if err != nil {
		// 框架业务错误状态码重置
		errCode := enums.ErrorCode(code.Code())
		switch code.Code() {
		case gcode.CodeNil.Code():
			errCode = enums.ErrorUnify // 统一错误状态码
		}

		// 直接返回
		response.Json(r, int(errCode), err.Error(), res)
		return
	}

	// 非200成功状态码
	if r.Response.Status != http.StatusOK {
		msg = http.StatusText(r.Response.Status)
		switch r.Response.Status {
		case http.StatusNotFound:
			code = gcode.CodeNotFound
		case http.StatusForbidden:
			code = gcode.CodeNotAuthorized
		default:
			code = gcode.CodeUnknown
		}
		// It creates error as it can be retrieved by other middlewares.
		err = gerror.NewCode(code, msg)
		r.SetError(err)
	} else {
		code = gcode.CodeOK
	}
	response.Json(r, code.Code(), msg, res)
}
